var bodyParser = require('body-parser');
const express = require('express');
var jwt = require('./dao/jwt')


const app = express()
const port = 3000

// 解析前端数据
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

// 获取静态文件路径
app.use('/data',express.static(__dirname+'/data'));
// app.use('/data',express.static(path.join(__dirname, '/data')));



app.get('/', (req, res) => res.send('你好 Hello World! 服务器启动状态'))

//设置跨域访问
// app.all('*', (req, res, next) => {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "X-Requested-With");
//     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//     res.header("X-Powered-By",' 3.2.1')
//     res.header("Content-Type", "application/json;charset=utf-8");
//     next();
// });



// token判断
app.use(function(req,res,next){
    // 目前判断条件有问题 这里应该需要先判断token，不然用户可以通过不传token绕过校验
    if((typeof(req.body.token) != 'undefined')){
        let {token} = req.body;
        let tokenMatch = jwt.verifyToken(token);
        console.log(token,tokenMatch)
        if(tokenMatch == 1){
            // 验证通过
            next()
        }else{
            res.send({status:401});
        }
    }else{
        next();
    }
})

// 引入路由
require('./router/index')(app);
require('./router/files')(app);

// 404页面
app.use(function(req,res,next){
    let err = new Error("Not Found");
    err.status = 404;
    next(err)
})

// 500 页面
app.use(function(err,req,res,next){
    res.status(err.status || 500)
    res.send(err.message);
})

app.listen(port, () => console.log(`服务已经启动在端口： ${port}!`))